<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>设置我的资料</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="../layui/css/layui.css" media="all">
  <link rel="stylesheet" href="../layui/css/admin.css" media="all">
</head>
<body>

  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-header">设置我的资料</div>
          <div class="layui-card-body" pad15>
            
            <div class="layui-form" lay-filter="layuiadmin-form-useradmin">
              <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-inline">
                  <input type="text" name="userId" readonly class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">不可修改。一般用于后台登入名</div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">昵称</label>
                <div class="layui-input-inline">
                  <input type="text" name="username" lay-verify="username" autocomplete="off" placeholder="请输入昵称" class="layui-input">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">院系</label>
                      <div class="layui-input-block" style="width: 220px;">
                        <select name="department">
                          <option value="0">不限</option>
                          <option value="1">大数据与基础科学学院</option>
                          <option value="2">石油工程学院</option>
                          <option value="3">智能制造与控制工程学院</option>
                          <option value="4">教育与现代媒体学院</option>
                        </select>
                      </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                  <input type="radio" name="sex" value="男" title="男">
                  <input type="radio" name="sex" value="女" title="女" checked>
                </div>
              </div>
              <div class="layui-form-item" lay-filter="birthday">
                <label class="layui-form-label">出生日期</label>
                 <div class="layui-input-inline">
                  <input type="text" name="birthday" id="date" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                 </div>
                </div>
              <div class="layui-form-item">
                <label class="layui-form-label">头像</label>
                <div class="layui-input-inline">
                  <input name="avatar" lay-verify="required" id="LAY_avatarSrc" placeholder="图片地址" class="layui-input">
                </div>
                <div class="layui-input-inline layui-btn-container" style="width: auto;">
                  <button type="button" class="layui-btn layui-btn-primary" id="LAY_avatarUpload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                  </button>
                  <button class="layui-btn layui-btn-primary" layadmin-event="avartatPreview">查看图片</button >
                </div>
             </div>
              <div class="layui-form-item">
                <label class="layui-form-label">手机</label>
                <div class="layui-input-inline">
                  <input type="text" name="phone" value="" lay-verify="phone" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-inline">
                  <input type="text" name="email" value="" lay-verify="email" autocomplete="off" class="layui-input">
                </div>
              </div>
              
              <div class="layui-form-item">
                <div class="layui-input-block">
                  <button class="layui-btn" lay-submit lay-filter="setmyinfo">确认修改</button>
                  
                </div>
              </div>
            </div>
            
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="../JS/utils/request.js"></script>
  <script src="../JS/utils/auth.js"></script>
  <script src="../layui/layui.all.js"></script>  
  <script>
 layui.laydate.render({
  elem: '#date'
});
  layui.use(['form', 'jquery','upload'],function(){
    let form = layui.form;
            let $ = layui.$;
            let upload = layui.upload

            // 获取院系下拉菜单的动态请求列表
            $.ajax({
              url: '/users/getDepartments', // 替换为实际接口地址
              type: 'GET',
              headers:{
              'Authorization':localStorage.getItem('token')
              },
              success: function(res) {
                console.log(res)
                if (res.code === 0) { // 根据实际接口返回状态码调整
                  var selectHtml = '';

                  // 遍历返回数据生成option
                  res.data.forEach(function(item) {
                    selectHtml += '<option value="' + item.departmentId + '">' + item.departmentName + '</option>';
                  });

                  // 更新select内容
                  $('select[name="department"]').html(selectHtml);

                  // 重新渲染表单
                  form.render('select');
                }
              },
              error: function(xhr, status, error) {
                console.error('分类数据获取失败:', error);
              }
            });
            // 初始化上传组件
            upload.render({
              elem: '#LAY_avatarUpload',
              url: '/users/upload', // 上传接口
              accept: 'images',   // 只允许选择图片文件
              acceptMime: 'image/*', // 限制文件类型
              size: 500,          // 500KB限制
              headers:{
              'Authorization': localStorage.getItem('token')
              },
              done: function(res){
                // console.log(res)
                if(res.code === 0) {
                  layer.msg('上传成功');
                  // 预览图片
                  $('#LAY_avatarSrc').val(res.data)
                } else {
                  layer.msg(res.msg || '上传失败');
                }
              },
              error: function(){
                layer.msg('上传失败，请检查网络连接');
              }
            });
            // 请求获取当前用户的基本信息
            $.ajax({
              url: '/users/list', // 替换为实际接口地址
              type: 'GET',
              headers:{
              'Authorization':localStorage.getItem('token')
              },
              data:{
                 userId:localStorage.getItem('userId')
              },
              success: function(res) {
                // console.log(res)
                // 填充表单数据
              form.val('layuiadmin-form-useradmin', {
                "userId": res.data.list[0].userId,
                "username": res.data.list[0].username,
                "sex": res.data.list[0].gender,
                "birthday": res.data.list[0].birthdate,
                "avatar":res.data.list[0].avatar,
                "department":res.data.list[0].departmentId,
                "phone":res.data.list[0].phone,
                "email":res.data.list[0].email,
              });  
              },
              error: function(xhr, status, error) {
                console.error('分类数据获取失败:', error);
              }
            });
            // 预览图片
            $('button[layadmin-event="avartatPreview"]').click(function(){
              const imgUrl = $('#LAY_avatarSrc').val().trim();
    
              if (!imgUrl) {
                layer.msg('请先输入图片地址');
                return;
              }

              layer.open({
                type: 1,
                title: '预览头像',
                skin: 'img-preview-layer',
                area: ['600px', '500px'], // 可调节弹窗尺寸
                content: `<div style="padding: 20px; text-align: center;">
                            <img src="${imgUrl}" 
                                style="max-width: 100%; max-height: 400px;"
                                onerror="this.src='//tva1.sinaimg.cn/large/0072Vf1pgy1foxkf5x7onj31hc0u0q6u.jpg'">
                          </div>`,
                success: function(layerElem) {
                  // 弹窗弹出后回调
                  const img = layerElem.find('img');
                  img.on('load', function() {
                    if (this.naturalWidth > 600 || this.naturalHeight > 400) {
                      layer.resize({
                        width: Math.min(this.naturalWidth + 40, 800),
                        height: Math.min(this.naturalHeight + 100, 600)
                      });
                    }
                  });
                }
              });
            })

            // 保存个人信息到数据库
            $('button[lay-filter="setmyinfo"]').click(function(){
               // 表单验证
               form.verify();
                
                // 获取表单数据
                let formData = {
                    username: $('input[name="username"]').val(),
                    gender:form.val('layuiadmin-form-useradmin').sex,
                    birthdate:$('input[name="birthday"]').val(),
                    userId:$('input[name="userId"]').val(),
                    departmentId:$('select[name="department"]').val(),
                    phone:$('input[name="phone"]').val(),
                    email: $('input[name="email"]').val(),
                    avatar:$('input[name="avatar"]').val()
                };
                // console.log(formData);
                

                // 发送AJAX请求
                $.ajax({
            url: '/users/update',
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            headers:{
              'Authorization':localStorage.getItem('token')
              },
            success: function(res){
              console.log(res)
              if(res.code === 0){
                const avatar = $('#LAY_avatarSrc').val()
                const username = $('input[name="username"]').val()
                // console.log(avatar);
                // layer.msg(res.data);
                localStorage.setItem('avatar',avatar)
                localStorage.setItem('username',username)
                parent.location.reload();
              } else {
                layer.msg(res.msg || '更新失败');
                
              }
            },
            error: function(xhr){
              layer.msg('请求失败: 院系不能为空！' + xhr.statusText);
              
            }
          });

            })


            
  });
  </script>
</body>
</html>